import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/event.dart';
import 'package:flutter_smart_heating/common/global.dart';
import 'package:flutter_smart_heating/pages/user/widget/user_header_view.dart';
import 'package:flutter_smart_heating/service/auth_service.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';

import 'widget/user_menu_view.dart';
import 'widget/user_substation_picker.dart';

class UserPage extends StatefulWidget {
  const UserPage({super.key});

  @override
  State<UserPage> createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> {
  bool get isDark => Theme.of(context).brightness == Brightness.dark;
  UserData user = AuthService.instance.user;
  ScrollController scrollController = ScrollController();
  double headerOpacity = 0;
  ValueNotifier badges = ValueNotifier<int>(0);
  dynamic eventBus;
  @override
  void initState() {
    scrollController.addListener(() {
      double opacity = max(0, min(1, scrollController.offset / 100));

      if (opacity != headerOpacity) {
        setState(() {
          headerOpacity = opacity;
        });
      }
    });
    eventBus =
        AppEvent().eventBus.on<RootNavigateChangeEvent>().listen((event) async {
      if (event.name == 'user') {
        await getBadges(context);
      }
    });
    badges.value = GlobalData.badges['messager'] ?? 0;
    App.report('/user');
    super.initState();
  }

  @override
  void dispose() {
    eventBus.cancel();
    super.dispose();
  }

  getBadges(context) async {
    await GlobalData.getBadge();
    badges.value = GlobalData.badges['messager'] ?? 0;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        leading: substationButtonView(),
        backgroundColor: UiTheme.of(context).match(
          light: UiTheme.primary.withOpacity(headerOpacity),
          dark: Theme.of(context)
              .scaffoldBackgroundColor
              .withOpacity(headerOpacity),
        ),
        foregroundColor: UiTheme(context).match(light: Colors.white),
        title: Text(
          '',
          style: TextStyle(
            color: Colors.white.withOpacity(
              headerOpacity,
            ),
          ),
        ),
        leadingWidth: 150,
        actions: [
          ValueListenableBuilder(
            valueListenable: badges,
            builder: (context, state, child) {
              return buttonView(
                icon: UiIcons.bell,
                badge: state,
                onTap: () async {
                  await App.push('/messager');
                  if (context.mounted) await getBadges(context);
                },
              );
            },
          ),
          buttonView(
            icon: isDark ? Icons.light_mode_outlined : Icons.dark_mode_outlined,
            onTap: () {
              UiTheme.toggle();
              setState(() {});
            },
          ),
          buttonView(
            icon: UiIcons.scanner,
            onTap: () {
              App.push('/qrcode');
            },
          ),
          const SizedBox(width: UiTheme.spacing)
        ],
      ),
      body: ListView(
        physics: const AlwaysScrollableScrollPhysics(),
        controller: scrollController,
        padding: EdgeInsets.zero,
        children: [
          UserHeaderView(user: user),
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: UiTheme.spacingX),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                UiLineBreak(),
                Padding(
                  padding: EdgeInsets.only(left: 15, bottom: 10, top: 5),
                  child: Text(
                    '常用功能',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 18,
                    ),
                  ),
                ),
                UserMenuView(),
                UiLineBreak(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget buttonView({
    required IconData icon,
    required Function()? onTap,
    int badge = 0,
  }) {
    double opacity = UiTheme(context).match(light: 0.3, dark: 0.15);
    return Container(
      margin: EdgeInsets.symmetric(
        horizontal: 6 - 3 * headerOpacity,
      ),
      height: 32,
      width: 32,
      child: IconButton(
        style: IconButton.styleFrom(
          padding: EdgeInsets.zero,
          backgroundColor: UiTheme.of(context)
              .matchColor(Colors.black, Colors.grey)
              .withOpacity(max(0, opacity - headerOpacity * 0.3)),
        ),
        onPressed: onTap,
        icon: Badge(
          backgroundColor: Colors.red,
          isLabelVisible: badge > 0,
          smallSize: 8,
          child: Icon(
            icon,
            size: 20,
          ),
        ),
      ),
    );
  }

  Widget substationButtonView() {
    double opacity = UiTheme(context).match(light: 0.3, dark: 0.15);
    return UiTap(
      onTap: () {
        if (AuthService.instance.user.isSubstation == false) {
          UserStationPicker.show(
            context,
            value: AuthService.instance.user.substationId,
            onConfirm: (item) async {
              setState(() {
                AuthService.instance.user.substationId = item['value'];
                AuthService.instance.user.substationName = item['label'];
              });
              App.push('switchTab://home');
              await 0.2.delay();
              Get.offAllNamed('/');
            },
          );
        }
      },
      child: Padding(
        padding: EdgeInsets.only(
          left: UiTheme.spacingX - headerOpacity * UiTheme.spacingX * 0.5,
        ),
        child: Center(
          child: Row(
            children: [
              Container(
                height: 32,
                padding: const EdgeInsets.symmetric(horizontal: 10),
                decoration: BoxDecoration(
                  color: UiTheme.of(context)
                      .matchColor(
                        Colors.black,
                        Colors.grey,
                      )
                      .withOpacity(
                        max(0, opacity - headerOpacity * 0.3),
                      ),
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const UiIcon(
                      UiIcons.location,
                      size: 16,
                    ),
                    const SizedBox(width: 3),
                    Text(AuthService.instance.user.substationName ?? '--'),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
